﻿using System;
using System.Windows;

namespace Asko.Lib.Convertes
{

    static class GraphConverterHelper
    {
        public static Point CalculateAttachPoint(Point s, Size sourceSize, Point t)
        {
            double[] sides = new double[4];
            double da = (t.Y - s.Y) / Math.Abs((t.X - s.X));
            double dx = (t.X - s.X), dy = (t.Y - s.Y);
            Point prest;
          
            prest = new Point(s.X, s.Y);            
            if (da >= -0.40 && da <= 0.40)
            {
                prest.Y = s.Y + (sourceSize.Height / 2);
                if (dx > 0)
                {
                    prest.X = s.X + sourceSize.Width;

                }
                else
                {
                prest.X = s.X;                
                }
            }
            else if (da > 0.40 || da < -0.40)
            {
                prest.X = s.X + sourceSize.Width / 2;
                if (da > 0)
                {
                    prest.Y = s.Y + sourceSize.Height;
                }
                else
                {
                    prest.Y = s.Y;
                }
            }
            sides[0] = (s.X - t.X) / (s.Y + (sourceSize.Height / 2) - t.Y);
            sides[1] = (s.X + (sourceSize.Width / 2) - t.X) / (s.Y - t.Y);
            sides[2] = (s.X + sourceSize.Width - t.X) / (s.Y + (sourceSize.Height / 2) - t.Y);
            sides[3] = (s.X + (sourceSize.Width / 2) - t.X) / (s.X + (sourceSize.Height) - t.Y);


            double fi = 0;
            for (int i = 0; i < 4; i++)
            {
                if (sides[i] <= 1)
                    fi = Math.Max(fi, sides[i]);
            }

            return prest;
        }
    }

}
